import Vue from 'vue'
import VueRouter from 'vue-router'
import { isLoggedIn } from '@/utils/auth.js'

Vue.use(VueRouter)

const routes = [
  { path: '/introduction', name: 'Introduction', component: () => import('../views/Introduction.vue')},
  { path: '/login', name: 'Login', component: () => import('../views/LoginPage.vue')},
  { path: '/register', name: 'Register', component: () => import('../views/RegisterPage.vue')},
  {
    path: '/',
    name: 'Manager',
    component: () => import('../views/Manager.vue'),
    redirect: '/introduction',  // 重定向到主页
    children: [
      { path: 'upload', name: 'Upload', component: () => import('../views/manager/UploadPage.vue')},
      { path: 'systemPaper', name: 'SystemPaper', component: () => import('../views/manager/SystemPdfPage.vue')},
      { path: 'myPaper', name: 'MyPaper', component: () => import('../views/manager/PaperManagementPage.vue')},
      { path: 'notes', name: 'Notes', component: () => import('../views/manager/NotesPage.vue')},
      { path: 'help', name: 'Help', component: () => import('../views/manager/HelpPage.vue')},
    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 需要登录的页面
  const requiresAuth = ['/upload', '/history', '/paperManagement', '/systemPdf', '/notes', '/help', '/account'];
  
  if (requiresAuth.includes(to.path)) {
    if (!isLoggedIn()) {
      // 未登录，跳转到登录页面
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router